package org.softmed.rest.admin.file;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Popup;

import org.softmed.swing.IconManager;

public class AskForNamePopup extends JDialog implements ActionListener {

	JPanel panel = new JPanel();
	JButton ok = new JButton("OK", IconManager.accept);
	JButton cancel = new JButton("Cancel", IconManager.cancel);
	JTextField filename = new JTextField();
	FileBrowser fileBrowser;
	String fullPath;
	int width = 30;
	int height = 30;

	Popup popup;
	private boolean directory;

	public AskForNamePopup(FileBrowser fileBrowser, String fullPath,
			boolean directory) {

		this.directory = directory;
		this.fileBrowser = fileBrowser;
		this.fullPath = fullPath;

//		setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
		setPreferredSize(new Dimension(500, 100));
		add(filename);
		addButton(ok);
		addButton(cancel);

	}

	protected void addButton(JButton button) {
		button.setPreferredSize(new Dimension(width, height));
		button.setMaximumSize(new Dimension(width, height));
		button.setMinimumSize(new Dimension(width, height));
		button.addActionListener(this);
		button.setEnabled(false);
		add(button);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		Object source = arg0.getSource();

		if (source == cancel) {

		} else {
			if (filename.getText() == null || filename.getText().length() == 0) {
				sendErrorPopup("Name Error", "Name can't be empty !");
			}

			try {
				if (directory)
					fileBrowser.createDirectory(fullPath, filename.getText());
				else
					fileBrowser.createFile(fullPath, filename.getText());
			} catch (Throwable t) {
				t.printStackTrace();
				sendFileIOErrorPopup(t.getMessage());
			}
			// TODO try to create the file/dir
			// if error, show popup
			// else
			// close the popup

			popup.hide();

		}

	}

	protected void sendFileIOErrorPopup(String text) {
		sendErrorPopup("File I/O Error", text);

	}

	protected void sendErrorPopup(String title, String text) {
		int duh = JOptionPane.showConfirmDialog(this, text, title,
				JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
	}

	public Popup getPopup() {
		return popup;
	}

	public void setPopup(Popup popup) {
		this.popup = popup;
	}

	public FileBrowser getFileBrowser() {
		return fileBrowser;
	}

	public void setFileBrowser(FileBrowser fileBrowser) {
		this.fileBrowser = fileBrowser;
	}

	public String getFullPath() {
		return fullPath;
	}

	public void setFullPath(String fullPath) {
		this.fullPath = fullPath;
	}

}
